package com.sczmgk.track.base;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.v4.content.res.ResourcesCompat;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.trace.Trace;
import com.baidu.trace.api.entity.OnEntityListener;
import com.baidu.trace.api.fence.FenceAlarmPushInfo;
import com.baidu.trace.api.fence.MonitoredAction;
import com.baidu.trace.api.track.LatestPoint;
import com.baidu.trace.api.track.LatestPointResponse;
import com.baidu.trace.api.track.OnTrackListener;
import com.baidu.trace.model.LocationMode;
import com.baidu.trace.model.OnTraceListener;
import com.baidu.trace.model.PushMessage;
import com.baidu.trace.model.StatusCodes;
import com.baidu.trace.model.TraceLocation;
import com.sczmgk.track.MyApp;
import com.sczmgk.track.R;
import com.sczmgk.track.constant.Constant;
import com.sczmgk.track.db.impl.UserDaoImpl;
import com.sczmgk.track.dialog.DialogFactory;
import com.sczmgk.track.dialog.MessageDialog;
import com.sczmgk.track.entity.CurrentLocation;
import com.sczmgk.track.entity.PaymentStyleInfos;
import com.sczmgk.track.entity.TrackBean;
import com.sczmgk.track.entity.User;
import com.sczmgk.track.entity.bean.RecordStatuData;
import com.sczmgk.track.httpUtils.MyHttp;
import com.sczmgk.track.receiver.TrackReceiver;
import com.sczmgk.track.test.MyCallback;
import com.sczmgk.track.utils.BitmapUtil;
import com.sczmgk.track.utils.CacheUtils;
import com.sczmgk.track.utils.CommonUtils;
import com.sczmgk.track.utils.MapUtil;
import com.sczmgk.track.utils.MyLog;
import com.sczmgk.track.utils.MyToast;
import com.sczmgk.track.utils.Tools;
import com.sczmgk.track.utils.ViewUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import static com.sczmgk.track.entity.CurrentLocation.latitude;
import static com.sczmgk.track.entity.CurrentLocation.longitude;

/**
 * Created by Administrator on 2017/9/29.
 */
public abstract class BaseMapActivity extends CheckPermissionBaseActivity implements View.OnClickListener {

    public static final int TRACING_ACITIVITY_TYPE = 1;
    public static final int TRACING_SEARCH_ACTIVITY_TYPE = 2;
    private static final int CUSTOM_TIME = 0;

    private Button mLocationBtn;
    private Button mEnlargeBtn;
    private Button mReduceBtn;
    private PopupWindow mPop;
    public MyApp trackApp = null;

    public ViewUtil viewUtil = null;

    public Button traceBtn = null;

//    public Button gatherBtn = null;

//    public NotificationManager notificationManager = null;

    public PowerManager powerManager = null;

    public PowerManager.WakeLock wakeLock = null;

    public TrackReceiver trackReceiver = null;

    /**
     * 地图工具
     */
    public MapUtil mapUtil = null;

    /**
     * 轨迹服务监听器
     */
    public OnTraceListener traceListener = null;

    /**
     * 轨迹监听器(用于接收纠偏后实时位置回调)
     */
    public OnTrackListener trackListener = null;

    /**
     * Entity监听器(用于接收实时定位回调)
     */
    public OnEntityListener entityListener = null;

    /**
     * 实时定位任务
     */
    public RealTimeHandler realTimeHandler = new RealTimeHandler();

    public RealTimeLocRunnable realTimeLocRunnable = null;

    public boolean isRealTimeRunning = true;

    public int notifyId = 0;

    /**
     * 打包周期
     */
    public int packInterval = Constant.DEFAULT_PACK_INTERVAL;
    public LinearLayout mLayoutSignContainer;
    public Button btnSearch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutResId());
        setRightBtnVisibility(View.VISIBLE);
        setRightBtnText(R.string.logout);
        setRightBtnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CacheUtils.cacheLoginStatus(BaseMapActivity.this,false);
                finish();
            }
        });
        MyLog.w(TAG, "activity oncreate");
        BitmapUtil.init();
        init();
        initTrace();
        initListener();
    }

    /**
     * 初始化支付类型的数据                                                                                               `
     */
    private void initStyleData() {

        paymentStyleInfos = new ArrayList<>();

        String[] arrays = getResources().getStringArray(R.array.select_time);
        for (int i = 0; i < arrays.length; i++) {

            PaymentStyleInfos zhifubao = new PaymentStyleInfos();
            zhifubao.payTitle = arrays[i];

            if (i == 0) {
                zhifubao.isSelect = true;
            } else {
                zhifubao.isSelect = false;
            }

            paymentStyleInfos.add(zhifubao);
        }

    }

    private void initTrace() {
        User loginUser = UserDaoImpl.getLoginUser(BaseMapActivity.this);
        if(loginUser != null){
            trackApp.entityName = loginUser.username;
        }

        trackApp.mTrace = new Trace(trackApp.serviceId, trackApp.entityName);
        trackApp.mTrace.setNotification(trackApp.notification);
    }



    private void init() {

        trackApp = (MyApp) getApplicationContext();
        viewUtil = new ViewUtil();
//        mapUtil = MapUtil.getInstance();
        mapUtil = new MapUtil();
        mapUtil.init((MapView) findViewById(R.id.tracing_mapView));
        btnSearch = (Button) findViewById(R.id.btn_go_sign);
        mLocationBtn = (Button) findViewById(R.id.bt_location);
        mEnlargeBtn = (Button) findViewById(R.id.bt_enlarge);
        mReduceBtn = (Button) findViewById(R.id.bt_raduce);
//        //TODO 模拟器需要给初始坐标,需要删除
//        latitude = 30.6451;
//        longitude = 104.038449;

        mapUtil.setCenter(trackApp);
        startRealTimeLoc(Constant.LOC_INTERVAL);
        powerManager = (PowerManager) trackApp.getSystemService(Context.POWER_SERVICE);

        traceBtn = (Button) findViewById(R.id.btn_trace);
//        gatherBtn = (Button) findViewById(R.id.btn_gather);

        traceBtn.setOnClickListener(this);
//        gatherBtn.setOnClickListener(this);
        setTraceBtnStyle();
//        setGatherBtnStyle();
//        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        setViewVisible(getMapType());

        isShowLeftView(getIsShowLeft());

        mapUtil.mapView.getChildAt(2).setPadding(0,0,Tools.dip2px(BaseMapActivity.this,23),Tools.dip2px(BaseMapActivity.this,100));
//        int x = Tools.dip2px(BaseMapActivity.this,20);
//        int y = Tools.getScreenHeight(BaseMapActivity.this)-Tools.dip2px(BaseMapActivity.this,25);
//        Point point = new Point(40,40);
//        mapUtil.mapView.setScaleControlPosition(point);
//        mapUtil.mapView.setZoomControlsPosition(new Point(Tools.dip2px(BaseMapActivity.this,20),Tools.getScreenHeight(BaseMapActivity.this)-Tools.dip2px(BaseMapActivity.this,25)));
//        mapUtil.mapView.setZoomControlsPosition(point);





    }

    protected abstract boolean getIsShowLeft();

    public abstract int getMapType();

    private void setViewVisible(int mapType) {
        switch (mapType) {
            case TRACING_ACITIVITY_TYPE:
                //主页
                break;
            case TRACING_SEARCH_ACTIVITY_TYPE:
                break;
            default:
                break;
        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.btn_trace:
                if (UserDaoImpl.getLoginUser(BaseMapActivity.this).imeistatus == User.SIGN_ENABLE) {
                    track();
                } else{
                    DialogFactory.warningDialog(BaseMapActivity.this,"没有激活无法使用该功能");
                }
                break;

//            case R.id.btn_gather:
//
//                break;

            default:
                break;
        }

    }

    /**
     * 开启服务
     */
    private void track() {
        if (trackApp.isTraceStarted) {
            //需要区分手动型与定时型
            int recordType = CacheUtils.getRecordType(BaseMapActivity.this);

            if(recordType == 0){//手动型
                MessageDialog messageDialog = DialogFactory.chooseDialog(BaseMapActivity.this, "确定要停止记录?", "是", "否", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        CacheUtils.setEnableStatus(BaseMapActivity.this, true);
                        mStopTrace();
                    }
                }, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        //
                    }
                });
                messageDialog.setTitle("提示");
                messageDialog.show();
            }else{
                MessageDialog messageDialog = DialogFactory.chooseDialog(BaseMapActivity.this, "记录未满"+recordType+"小时,"+"确定要停止记录?", "是", "否", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        CacheUtils.setEnableStatus(BaseMapActivity.this, true);
                        mStopTrace();
                    }
                }, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        //
                    }
                });
                messageDialog.setTitle("提示");
                messageDialog.show();
            }



        } else {
            //弹出pop
            showMpop();

        }


    }

    /**
     * 停止记录
     */
    private void mStopTrace() {
        trackApp.mClient.stopTrace(trackApp.mTrace, traceListener);
        stopRealTimeLoc();
    }

    private void showMpop() {
        dismissMPup();

        if (paymentStyleInfos == null) {
            initStyleData();
        }
        if (mPop == null) {
            initMpop();
        }

        // 显示窗口
        mPop.showAtLocation(baseLayout, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    /**
     * 初始化pop
     */
    private void initMpop() {
        mPop = new PopupWindow(this);
        View rootView = View.inflate(BaseMapActivity.this, R.layout.layout_select_time, null);
        ListView lv = (ListView) rootView.findViewById(R.id.lv_select_time);
        ImageView iv = (ImageView) rootView.findViewById(R.id.iv_close);
        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismissMPup();
            }
        });
        TextView sure = (TextView) rootView.findViewById(R.id.tv_time_sure);
        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO  判断网络是否可用
                //1.打开轨迹
                //2.调用接口
                //3.关闭
                if(!CommonUtils.isNetworkAvailable(BaseMapActivity.this)){
                    MyToast.show(BaseMapActivity.this,"请检查网络!");
                }else{
                    CacheUtils.setRecordType(BaseMapActivity.this,getRecordTime());
                    mStartTrace();
                    dismissMPup();
                }
;
            }
        });
        final MAdapter madapter = new MAdapter();
        lv.setAdapter(madapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                for (int i = 0; i < paymentStyleInfos.size(); i++) {
                    PaymentStyleInfos infos = paymentStyleInfos.get(i);
                    if (i == position && !infos.isSelect) {
                        infos.isSelect = true;
                    } else if (i == position && infos.isSelect) {
                        infos.isSelect = true;
                    } else {
                        infos.isSelect = false;
                    }
                }
                madapter.notifyDataSetChanged();
            }
        });
        mPop.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
        mPop.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
        mPop.setFocusable(true);
        mPop.setContentView(rootView);
        mPop.setOutsideTouchable(true);
        mPop.setBackgroundDrawable(new ColorDrawable(BaseMapActivity.this.getResources().getColor(R.color.activity_item_alpha)));
        mPop.setAnimationStyle(R.style.mypopwindow_anim_style);
    }

    /**
     * 开始记录轨迹
     */
    private void mStartTrace() {
        MyLog.d(TAG,"开始记录");
        trackApp.mClient.startTrace(trackApp.mTrace, traceListener);
        if (Constant.DEFAULT_PACK_INTERVAL != packInterval) {
            stopRealTimeLoc();
            startRealTimeLoc(packInterval);
        }
    }


    public void dismissMPup() {
        if (null != mPop && mPop.isShowing()) {
            mPop.dismiss();
        }
    }

    private List<PaymentStyleInfos> paymentStyleInfos;

    /**
     * 支付方式的adapter
     */
    private class MAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return (paymentStyleInfos == null ? 0 : paymentStyleInfos.size());
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {

            view = View.inflate(BaseMapActivity.this, R.layout.item_payment_style, null);


            TextView tvItemTitle = (TextView) view.findViewById(R.id.tv_item_payment_title);

            TextView tvItemHint = (TextView) view.findViewById(R.id.tv_item_payment_hint);

            ImageView ivSelect = (ImageView) view.findViewById(R.id.iv_item_payment_select);

            PaymentStyleInfos infos = paymentStyleInfos.get(i);

            tvItemTitle.setText(infos.payTitle);

            tvItemHint.setText(infos.payHint);

            ivSelect.setImageResource(infos.isSelect ? R.drawable.time_select : R.color.transparent);

            return view;
        }
    }

    /**
     * 开始采集
     */
    private void gather() {
        //开启采集

        if (trackApp.isGatherStarted) {
            trackApp.mClient.stopGather(traceListener);
        } else {
            trackApp.mClient.startGather(traceListener);
        }
    }


    /**
     * 设置服务按钮样式
     */
    private void setTraceBtnStyle() {
        boolean isTraceStarted = trackApp.trackConf.getBoolean("is_trace_started", false);
        if (isTraceStarted) {
            traceBtn.setBackground(ResourcesCompat.getDrawable(getResources(),
                    R.drawable.track_stop, null));
        } else {
            traceBtn.setBackground(ResourcesCompat.getDrawable(getResources(),
                    R.drawable.track_start, null));
        }
    }

//    /**
//     * 设置采集按钮样式
//     */
//    private void setGatherBtnStyle() {
//        boolean isGatherStarted = trackApp.trackConf.getBoolean("is_gather_started", false);
//        if (isGatherStarted) {
//            gatherBtn.setText(R.string.stop_gather);
//            gatherBtn.setTextColor(ResourcesCompat.getColor(getResources(), R.color.white, null));
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
//                gatherBtn.setBackground(ResourcesCompat.getDrawable(getResources(),
//                        R.drawable.bg_btn_sure, null));
//            } else {
//                gatherBtn.setBackgroundDrawable(ResourcesCompat.getDrawable(getResources(),
//                        R.drawable.bg_btn_sure, null));
//            }
//        } else {
//            gatherBtn.setText(R.string.start_gather);
//            gatherBtn.setTextColor(ResourcesCompat.getColor(getResources(), R.color.layout_title, null));
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
//                gatherBtn.setBackground(ResourcesCompat.getDrawable(getResources(),
//                        R.drawable.bg_btn_cancel, null));
//            } else {
//                gatherBtn.setBackgroundDrawable(ResourcesCompat.getDrawable(getResources(),
//                        R.drawable.bg_btn_cancel, null));
//            }
//        }
//    }

    /**
     * 实时定位任务
     *
     * @author baidu
     */
    class RealTimeLocRunnable implements Runnable {

        private int interval = 0;

        public RealTimeLocRunnable(int interval) {
            this.interval = interval;
        }

        @Override
        public void run() {
            if (isRealTimeRunning) {
                trackApp.getCurrentLocation(entityListener, trackListener);
                realTimeHandler.postDelayed(this, interval * 1000);
            }
        }
    }

    public void startRealTimeLoc(int interval) {
        isRealTimeRunning = true;
        realTimeLocRunnable = new RealTimeLocRunnable(interval);
        realTimeHandler.post(realTimeLocRunnable);
    }

    public void stopRealTimeLoc() {
        isRealTimeRunning = false;
        if (null != realTimeHandler && null != realTimeLocRunnable) {
            realTimeHandler.removeCallbacks(realTimeLocRunnable);
        }
        trackApp.mClient.stopRealTimeLoc();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (null == data) {
            return;
        }

        if (data.hasExtra("locationMode")) {
            LocationMode locationMode = LocationMode.valueOf(data.getStringExtra("locationMode"));
            trackApp.mClient.setLocationMode(locationMode);
        }

        if (data.hasExtra("isNeedObjectStorage")) {
            boolean isNeedObjectStorage = data.getBooleanExtra("isNeedObjectStorage", false);
            trackApp.mTrace.setNeedObjectStorage(isNeedObjectStorage);
        }

        if (data.hasExtra("gatherInterval") && data.hasExtra("packInterval")) {
            int gatherInterval = data.getIntExtra("gatherInterval", Constant.DEFAULT_GATHER_INTERVAL);
            int packInterval = data.getIntExtra("packInterval", Constant.DEFAULT_PACK_INTERVAL);
            BaseMapActivity.this.packInterval = packInterval;
            trackApp.mClient.setInterval(gatherInterval, packInterval);
        }

        //        if (data.hasExtra("supplementMode")) {
        //            mSupplementMode = SupplementMode.valueOf(data.getStringExtra("supplementMode"));
        //        }
    }

    public void initListener() {

        mLocationBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                trackApp.getCurrentLocation(entityListener, trackListener);
            }
        });

        mEnlargeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                float zoomLevel = mapUtil.baiduMap.getMapStatus().zoom;

                if(zoomLevel<=18){
//                  MapStatusUpdateFactory.zoomIn();
                    mapUtil.baiduMap.setMapStatus(MapStatusUpdateFactory.zoomIn());
                    mReduceBtn.setEnabled(true);
                }else{
                    Toast.makeText(BaseMapActivity.this, "已经放至最大！", Toast.LENGTH_SHORT).show();
                    mEnlargeBtn.setEnabled(false);
                }
            }
        });

        mReduceBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                float zoomLevel = mapUtil.baiduMap.getMapStatus().zoom;
                if(zoomLevel>4){
                    mapUtil.baiduMap.setMapStatus(MapStatusUpdateFactory.zoomOut());
                    mEnlargeBtn.setEnabled(true);
                }else{
                    mReduceBtn.setEnabled(false);
                    Toast.makeText(BaseMapActivity.this, "已经缩至最小！", Toast.LENGTH_SHORT).show();
                }
            }
        });
        trackListener = new OnTrackListener() {

            @Override
            public void onLatestPointCallback(LatestPointResponse response) {
                if (StatusCodes.SUCCESS != response.getStatus()) {
                    return;
                }

                LatestPoint point = response.getLatestPoint();
                if (null == point || CommonUtils.isZeroPoint(point.getLocation().getLatitude(), point.getLocation()
                        .getLongitude())) {
                    return;
                }

                LatLng currentLatLng = mapUtil.convertTrace2Map(point.getLocation());
                if (null == currentLatLng) {
                    return;
                }
                CurrentLocation.locTime = point.getLocTime();
                latitude = currentLatLng.latitude;
                longitude = currentLatLng.longitude;

                if (null != mapUtil) {
                    mapUtil.updateStatus(currentLatLng, true);
                }
            }
        };

        entityListener = new OnEntityListener() {

            @Override
            public void onReceiveLocation(TraceLocation location) {


                if (StatusCodes.SUCCESS != location.getStatus() || CommonUtils.isZeroPoint(location.getLatitude(),
                        location.getLongitude())) {
                    return;
                }
                LatLng currentLatLng = mapUtil.convertTraceLocation2Map(location);
                if (null == currentLatLng) {
                    return;
                }
                CurrentLocation.locTime = CommonUtils.toTimeStamp(location.getTime());
                latitude = currentLatLng.latitude;
                longitude = currentLatLng.longitude;
                MyLog.d(TAG, "实时定位回调    lat: " + latitude + "        long: " + longitude);

                if (null != mapUtil) {
                    mapUtil.updateStatus(currentLatLng, true);
                }

            }

        };

        traceListener = new OnTraceListener() {

            /**
             * 绑定服务回调接口
             * @param errorNo  状态码
             * @param message 消息
             *                <p>
             *                <pre>0：成功 </pre>
             *                <pre>1：失败</pre>
             */
            @Override
            public void onBindServiceCallback(int errorNo, String message) {
//                viewUtil.showToast(BaseMapActivity.this,
//                        String.format("onBindServiceCallback, errorNo:%d, message:%s ", errorNo, message));
            }

            /**
             * 开启服务回调接口
             * @param errorNo 状态码
             * @param message 消息
             *                <p>
             *                <pre>0：成功 </pre>
             *                <pre>10000：请求发送失败</pre>
             *                <pre>10001：服务开启失败</pre>
             *                <pre>10002：参数错误</pre>
             *                <pre>10003：网络连接失败</pre>
             *                <pre>10004：网络未开启</pre>
             *                <pre>10005：服务正在开启</pre>
             *                <pre>10006：服务已开启</pre>
             */
            @Override
            public void onStartTraceCallback(int errorNo, String message) {
                if (StatusCodes.SUCCESS == errorNo || StatusCodes.START_TRACE_NETWORK_CONNECT_FAILED <= errorNo) {
                    trackApp.isTraceStarted = true;
                    SharedPreferences.Editor editor = trackApp.trackConf.edit();
                    editor.putBoolean("is_trace_started", true);
                    editor.apply();
                    setTraceBtnStyle();
                    registerReceiver();
                }
//                viewUtil.showToast(BaseMapActivity.this,
//                        String.format("onStartTraceCallback, errorNo:%d, message:%s ", errorNo, message));
                gather();
            }

            /**
             * 停止服务回调接口
             * @param errorNo 状态码
             * @param message 消息
             *                <p>
             *                <pre>0：成功</pre>
             *                <pre>11000：请求发送失败</pre>
             *                <pre>11001：服务停止失败</pre>
             *                <pre>11002：服务未开启</pre>
             *                <pre>11003：服务正在停止</pre>
             */
            @Override
            public void onStopTraceCallback(int errorNo, String message) {
                if (StatusCodes.SUCCESS == errorNo || StatusCodes.CACHE_TRACK_NOT_UPLOAD == errorNo) {
                    trackApp.isTraceStarted = false;
                    trackApp.isGatherStarted = false;
                    // 停止成功后，直接移除is_trace_started记录（便于区分用户没有停止服务，直接杀死进程的情况）
                    SharedPreferences.Editor editor = trackApp.trackConf.edit();
                    editor.remove("is_trace_started");
                    editor.remove("is_gather_started");
                    editor.apply();
                    setTraceBtnStyle();
//                    setGatherBtnStyle();
                    unregisterPowerReceiver();
                }
//                viewUtil.showToast(BaseMapActivity.this,
//                        String.format("onStopTraceCallback, errorNo:%d, message:%s ", errorNo, message));

                /**
                 * 不是正常停止则不上报停止
                 */
                if (CacheUtils.getEnableStatus(BaseMapActivity.this)) {

                    MyLog.d(TAG, "正常停止,上传服务器");

                    stopRecord();
                }
            }

            /**
             * 开启采集回调接口
             * @param errorNo 状态码
             * @param message 消息
             *                <p>
             *                <pre>0：成功</pre>
             *                <pre>12000：请求发送失败</pre>
             *                <pre>12001：采集开启失败</pre>
             *                <pre>12002：服务未开启</pre>
             */
            @Override
            public void onStartGatherCallback(int errorNo, String message) {
                if (StatusCodes.SUCCESS == errorNo || StatusCodes.GATHER_STARTED == errorNo) {
                    trackApp.isGatherStarted = true;
                    SharedPreferences.Editor editor = trackApp.trackConf.edit();
                    editor.putBoolean("is_gather_started", true);
                    editor.apply();
//                    setGatherBtnStyle();
                }
//                viewUtil.showToast(BaseMapActivity.this,
//                        String.format("onStartGatherCallback, errorNo:%d, message:%s ", errorNo, message));
                //TODO 调用 接口开始记录,j需要判断是否为重新打开App

                if (!CacheUtils.getRecordStatus(BaseMapActivity.this)) {
                    startRecord();
                }
                //取得定时时间
                if (getTimerLength() != -1) {
                    MyLog.i(TAG, "开启定时器");
                    Timer timer = new Timer();
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            CacheUtils.setEnableStatus(BaseMapActivity.this, true);
                            MyLog.d(TAG, "定时关闭记录");
                            mStopTrace();
                        }
                    }, getTimerLength());
                } else {
                    MyLog.e(TAG, "手动关闭,不需要开启定时器");
                }
            }

            /**
             * 停止采集回调接口
             * @param errorNo 状态码
             * @param message 消息
             *                <p>
             *                <pre>0：成功</pre>
             *                <pre>13000：请求发送失败</pre>
             *                <pre>13001：采集停止失败</pre>
             *                <pre>13002：服务未开启</pre>
             */
            @Override
            public void onStopGatherCallback(int errorNo, String message) {
                if (StatusCodes.SUCCESS == errorNo || StatusCodes.GATHER_STOPPED == errorNo) {
                    trackApp.isGatherStarted = false;
                    SharedPreferences.Editor editor = trackApp.trackConf.edit();
                    editor.remove("is_gather_started");
                    editor.apply();
//                    setGatherBtnStyle();
                }
//                viewUtil.showToast(BaseMapActivity.this, String.format("onStopGatherCallback, errorNo:%d, message:%s ", errorNo, message));

            }

            /**
             * 推送消息回调接口
             *
             * @param messageType 状态码
             * @param pushMessage 消息
             *                  <p>
             *                  <pre>0x01：配置下发</pre>
             *                  <pre>0x02：语音消息</pre>
             *                  <pre>0x03：服务端围栏报警消息</pre>
             *                  <pre>0x04：本地围栏报警消息</pre>
             *                  <pre>0x05~0x40：系统预留</pre>
             *                  <pre>0x41~0xFF：开发者自定义</pre>
             */
            @Override
            public void onPushCallback(byte messageType, PushMessage pushMessage) {
                if (messageType < 0x03 || messageType > 0x04) {
//                    viewUtil.showToast(BaseMapActivity.this, pushMessage.getMessage());
                    return;
                }
                FenceAlarmPushInfo alarmPushInfo = pushMessage.getFenceAlarmPushInfo();
                if (null == alarmPushInfo) {
//                    viewUtil.showToast(BaseMapActivity.this, String.format("onPushCallback, messageType:%d, messageContent:%s ", messageType, pushMessage));
                    return;
                }
                StringBuffer alarmInfo = new StringBuffer();
                alarmInfo.append("您于")
                        .append(CommonUtils.getHMS(alarmPushInfo.getCurrentPoint().getLocTime() * 1000))
                        .append(alarmPushInfo.getMonitoredAction() == MonitoredAction.enter ? "进入" : "离开")
                        .append(messageType == 0x03 ? "云端" : "本地")
                        .append("围栏：").append(alarmPushInfo.getFenceName());

                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
                    //TODO
//                    Notification notification = new Notification.Builder(trackApp)
//                            .setContentTitle(getResources().getString(R.string.alarm_push_title))
//                            .setContentText(alarmInfo.toString())
//                            .setSmallIcon(R.drawable.icon_app)
//                            .setWhen(System.currentTimeMillis()).build();
//                    notificationManager.notify(notifyId++, notification);
                }
            }

            @Override
            public void onInitBOSCallback(int errorNo, String message) {
//                viewUtil.showToast(BaseMapActivity.this,
//                        String.format("onInitBOSCallback, errorNo:%d, message:%s ", errorNo, message));
            }
        };
    }

    private TrackBean recordStadu = null;

    /**
     * 检查用户记录轨迹状态
     */
    protected void checkRecordStatus() {
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("userid", CacheUtils.getLoginUserid(BaseMapActivity.this));
        MyHttp.requestDataT(BaseMapActivity.this, Constant.CHECK_RECORD_STATUS_URL, MyHttp.POST, null, dataMap, null, false, null, new MyCallback<RecordStatuData>() {
            @Override
            public void onSuccess(RecordStatuData o) {
                //取出状态
                recordStadu = o.data;
                //没有结束则计算需要定时时间

                if (recordStadu.isend == 0) {
                    //设置不需要上传服务器
                    CacheUtils.setREcordStatus(BaseMapActivity.this, true);
                    CacheUtils.setRecordType(BaseMapActivity.this,recordStadu.runtimelength);
                    //开启记录
                    //判断网络是否可用
                    mStartTrace();
                    //开启定时器

                }

            }

            @Override
            public void onUnknownError() {

            }

            @Override
            public void onError(String msg) {

            }

            @Override
            public void onSuccess() {

            }
        });
    }

    /**
     * 上传开始记录到后台
     */
    private void startRecord() {
        MyLog.i(TAG, "------------提交开始记录");
        mapUtil.getAddress(new LatLng(latitude, longitude), new MapUtil.OnGetGeoCallback() {
            @Override
            public void onSuccess(String address) {
                Map<String, Object> dataMap = new HashMap<>();
                dataMap.put("userid", CacheUtils.getLoginUserid(BaseMapActivity.this));
                dataMap.put("startaddress", address);
                dataMap.put("runtimelength", getRecordTime());
                MyHttp.requestDataT(BaseMapActivity.this, Constant.ADD_LOG_URL, MyHttp.POST, null, dataMap, null, false, null, new MyCallback() {
                    @Override
                    public void onSuccess(Object o) {

                    }

                    @Override
                    public void onUnknownError() {

                    }

                    @Override
                    public void onError(String msg) {

                    }

                    @Override
                    public void onSuccess() {

                    }
                });
            }

            @Override
            public void onFail() {

            }

            @Override
            public void onSuccess(PoiInfo poi) {

            }

            @Override
            public void onSuccess(List<PoiInfo> poiinfs) {

            }
        });

    }

    /**
     * 向后台提交停止记录
     */
    private void stopRecord() {
        MyLog.e(TAG, "------------提交停止记录");
        mapUtil.getAddress(new LatLng(latitude, longitude), new MapUtil.OnGetGeoCallback() {
            @Override
            public void onSuccess(String address) {
             if(Tools.isEmpty(address)){
                MyToast.show(BaseMapActivity.this,"没有取到位置信息,不能停止,请稍后再试!");
            }else{
                Map<String, Object> dataMap = new HashMap<>();
                dataMap.put("endaddress", address);
                dataMap.put("userid", CacheUtils.getLoginUserid(BaseMapActivity.this));
                MyHttp.requestDataT(BaseMapActivity.this, Constant.CLOSE_LOG_URL, MyHttp.POST, null, dataMap, null, false, null, new MyCallback() {
                    @Override
                    public void onSuccess(Object o) {

                    }

                    @Override
                    public void onUnknownError() {

                    }

                    @Override
                    public void onError(String msg) {

                    }

                    @Override
                    public void onSuccess() {
                        MyLog.d(TAG, "提交停止记录成功");
                        CacheUtils.setREcordStatus(BaseMapActivity.this, false);
                        //TODO 关闭鹰眼服务
                    }
                });
            }
            }

            @Override
            public void onFail() {

            }

            @Override
            public void onSuccess(PoiInfo poi) {

            }

            @Override
            public void onSuccess(List<PoiInfo> poiinfs) {

            }
        });

    }

    private String getCurrAdress() {
        //TODO 调用地理反查

        return "这是一个测试地址";
    }

    /**
     * 取得记录时间
     */
    private int getRecordTime() {
        int time = CUSTOM_TIME;
        if (paymentStyleInfos.get(0).isSelect) {
            time = 4;
        }
        if (paymentStyleInfos.get(1).isSelect) {
            time = 8;
        }
        return time;
    }

    /**
     * 获取定时时间 ms
     * @return
     */
    private long getTimerLength() {


        long result = 0;
        //1.用户选择的时间
        //2.服务器拉取计算的时间
        if (CacheUtils.getRecordStatus(BaseMapActivity.this)) {
            //取服务器计算的时间
            if (recordStadu != null) {
                if (recordStadu.runtimelength == CUSTOM_TIME) {//用户手动停止,将它设置为最长时间8小时关闭
                    result = Tools.getTo22H(recordStadu.systime,recordStadu.starttime);
                } else {
                    //开始的时间
                    long l = Tools.convert2long(recordStadu.starttime);
                    //手机当前的时间
                    long currTime = Tools.convert2long(recordStadu.systime);
                    //需要的时间
                    long time = l + (recordStadu.runtimelength * 60 * 60 * 1000);
                    //剩余的时间
                    if (time > currTime) {
                        result = time - currTime;
                    }
                }
            }
        } else {
            //取用户选择的时间
            if (getRecordTime() == CUSTOM_TIME) {

                result = Tools.getTo22H();

            } else {

                result = getRecordTime() * 60 * 60 * 1000;
            }
            MyLog.i(TAG, "用户选择时间: " + result);
        }

        if(result == 0){
            CacheUtils.setRecordType(BaseMapActivity.this,0);
        }
        MyLog.d(TAG,"定时时间 : "+result/1000/60+ "分钟");
        return result;
    }

    static class RealTimeHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    }

    /**
     * 注册广播（电源锁、GPS状态）
     */
    private void registerReceiver() {
        if (trackApp.isRegisterReceiver) {
            return;
        }

        if (null == wakeLock) {
            wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "track upload");
        }
        if (null == trackReceiver) {
            trackReceiver = new TrackReceiver(wakeLock);
        }

        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_USER_PRESENT);
        filter.addAction(StatusCodes.GPS_STATUS_ACTION);
        trackApp.registerReceiver(trackReceiver, filter);
        trackApp.isRegisterReceiver = true;

    }

    private void unregisterPowerReceiver() {
        if (!trackApp.isRegisterReceiver) {
            return;
        }
        if (null != trackReceiver) {
            trackApp.unregisterReceiver(trackReceiver);
        }
        trackApp.isRegisterReceiver = false;
    }

    @Override
    protected void onStart() {
        super.onStart();
//        startRealTimeLoc(packInterval);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapUtil.onResume();

        checkLocation();
        // 在Android 6.0及以上系统，若定制手机使用到doze模式，请求将应用添加到白名单。
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String packageName = trackApp.getPackageName();
            boolean isIgnoring = powerManager.isIgnoringBatteryOptimizations(packageName);
            if (!isIgnoring) {
                Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                intent.setData(Uri.parse("package:" + packageName));
                try {
                    startActivity(intent);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapUtil.onPause();

    }

    @Override
    protected void onStop() {
        super.onStop();
//        stopRealTimeLoc();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyLog.e(TAG, "activity  ondDestroy");
        mapUtil.clear();
        stopRealTimeLoc();
        mStopTrace();
        //清除用户信息
    }


    @Override
    public void handleMessage(Message msg) {

    }

    @Override
    public boolean getIsNeedLogin() {
        return false;
    }

    @Override
    public void onSelectedPhonePermission(String phoneNumber) {

    }

    @Override
    public void onSelectedStroage(int position) {

    }

    @Override
    public void onSelectCamera(int position) {

    }

    public abstract int getLayoutResId();
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addCategory(Intent.CATEGORY_HOME);
            startActivity(intent);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
